<script setup lang="ts">
import { ref, onMounted, h } from 'vue';
import { Page } from '@vben/common-ui';
import { NDataTable, NPagination, NButton, NModal, NForm, NFormItem, NInput, NSelect, NDatePicker, NInputNumber, useMessage, NTag } from 'naive-ui';
import { getModelRequestRecordList, type ModelRequestRecord } from '#/api/model-lake/request-records';

const columns = [
  { key: 'request_id', title: '请求ID', width: 200 },
  { key: 'model_name', title: '模型名称' },
  { key: 'channel_id', title: '渠道ID' },
  { key: 'channel_account_id', title: '渠道账号ID' },
  { key: 'user_id', title: '用户ID' },
  {
    key: 'is_success',
    title: '是否成功',
    render: (row: any) => h(NTag, {
      type: row.is_success ? 'success' : 'error'
    }, {
      default: () => row.is_success ? '成功' : '失败'
    })
  },
  { key: 'total_tokens', title: '总Token数' },
  { key: 'cost', title: '费用', render: (row: any) => `¥${(row.cost || 0).toFixed(4)}` },
  { key: 'created_at', title: '创建时间' },
  {
    key: 'actions',
    title: '操作',
    render(row: any) {
      return [
        h(NButton, { size: 'small', type: 'primary', onClick: () => handleDetail(row) }, { default: () => '详情' }),
      ];
    },
  },
];

// 详情表格列定义
const detailColumns = [
  { key: 'field', title: '字段' },
  { key: 'value', title: '值' },
];

const data = ref<ModelRequestRecord[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const message = useMessage();

// 搜索条件
const searchForm = ref({
  request_id: '',
  model_name: '',
  channel_id: undefined as number | undefined,
  user_id: '',
  is_success: undefined as boolean | undefined,
  start_time: null as number | null,
  end_time: null as number | null,
});

// 弹窗相关
const showModal = ref(false);
const modalTitle = ref('');
const formModel = ref<ModelRequestRecord>({
  request_id: '',
  channel_id: 0,
  channel_account_id: 0,
  model_name: '',
  is_success: false,
  prompt_tokens: 0,
  completion_tokens: 0,
  total_tokens: 0,
  cost: 0
});
const formLoading = ref(false);
const detailData = ref<any[]>([]);

async function fetchData() {
  loading.value = true;
  try {
    const params: any = {
      page: page.value,
      size: pageSize.value,
      ...searchForm.value,
      start_time: searchForm.value.start_time ? new Date(searchForm.value.start_time).toISOString() : undefined,
      end_time: searchForm.value.end_time ? new Date(searchForm.value.end_time).toISOString() : undefined,
    };

    // 过滤掉空值
    Object.keys(params).forEach((key: string) => {
      if (params[key] === null || params[key] === '' || params[key] === undefined) {
        delete params[key];
      }
    });

    const res = await getModelRequestRecordList(params);
    data.value = res.result || [];
    total.value = res.result?.length || 0; // API文档显示返回数组，没有total字段
  } catch (error) {
    console.error('获取模型请求记录列表失败:', error);
    message.error('获取模型请求记录列表失败');
    data.value = [];
  } finally {
    loading.value = false;
  }
}

onMounted(fetchData);

function handlePageChange(p: number) {
  page.value = p;
  fetchData();
}

function handlePageSizeChange(s: number) {
  pageSize.value = s;
  page.value = 1;
  fetchData();
}

function handleSearch() {
  page.value = 1;
  fetchData();
}

function handleReset() {
  searchForm.value = {
    request_id: '',
    model_name: '',
    channel_id: undefined,
    user_id: '',
    is_success: undefined,
    start_time: null,
    end_time: null,
  };
  page.value = 1;
  fetchData();
}

async function handleDetail(row: ModelRequestRecord) {
  modalTitle.value = '请求记录详情';
  formLoading.value = true;
  try {
    formModel.value = { ...row };

    // 转换为表格数据格式
    detailData.value = [
      { field: '请求ID', value: formModel.value.request_id || '-' },
      { field: '父请求ID', value: formModel.value.parent_request_id || '-' },
      { field: 'Agent ID', value: formModel.value.agent_id || '-' },
      { field: 'Chat ID', value: formModel.value.chat_id || '-' },
      { field: '渠道ID', value: formModel.value.channel_id || '-' },
      { field: '渠道账号ID', value: formModel.value.channel_account_id || '-' },
      { field: '用户ID', value: formModel.value.user_id || '-' },
      { field: '模型名称', value: formModel.value.model_name || '-' },
      { field: '是否成功', value: formModel.value.is_success ? '成功' : '失败' },
      { field: '错误代码', value: formModel.value.error_code || '-' },
      { field: '错误消息', value: formModel.value.error_message || '-' },
      { field: '提示词Token数', value: formModel.value.prompt_tokens || 0 },
      { field: '完成Token数', value: formModel.value.completion_tokens || 0 },
      { field: '总Token数', value: formModel.value.total_tokens || 0 },
      { field: '费用', value: `¥${(formModel.value.cost || 0).toFixed(4)}` },
      { field: '创建时间', value: formModel.value.created_at || '-' },
      { field: '创建者', value: formModel.value.created_by || '-' },
    ];

    showModal.value = true;
  } catch (error) {
    console.error('获取详情失败:', error);
    message.error('获取详情失败');
  } finally {
    formLoading.value = false;
  }
}
</script>

<template>
  <Page description="模型请求记录管理" title="模型请求记录管理">
    <!-- 搜索条件 -->
    <div class="mb-4">
      <NForm :model="searchForm" inline>
        <NFormItem label="请求ID">
          <NInput v-model:value="searchForm.request_id" placeholder="请输入请求ID" style="width: 200px" />
        </NFormItem>
        <NFormItem label="模型名称">
          <NInput v-model:value="searchForm.model_name" placeholder="请输入模型名称" style="width: 200px" />
        </NFormItem>
        <NFormItem label="渠道ID">
          <NInputNumber v-model:value="searchForm.channel_id" placeholder="请输入渠道ID" style="width: 150px" />
        </NFormItem>
        <NFormItem label="用户ID">
          <NInput v-model:value="searchForm.user_id" placeholder="请输入用户ID" style="width: 200px" />
        </NFormItem>
        <NFormItem label="是否成功">
          <NSelect
            v-model:value="searchForm.is_success"
            placeholder="请选择"
            :options="[
              { label: '全部', value: undefined },
              { label: '成功', value: true },
              { label: '失败', value: false }
            ]"
            style="width: 120px"
          />
        </NFormItem>
        <NFormItem label="开始时间">
          <NDatePicker v-model:value="searchForm.start_time" type="datetime" placeholder="选择开始时间" style="width: 200px" />
        </NFormItem>
        <NFormItem label="结束时间">
          <NDatePicker v-model:value="searchForm.end_time" type="datetime" placeholder="选择结束时间" style="width: 200px" />
        </NFormItem>
        <NFormItem>
          <NButton type="primary" @click="handleSearch">搜索</NButton>
          <NButton class="ml-2" @click="handleReset">重置</NButton>
        </NFormItem>
      </NForm>
    </div>

    <NDataTable :columns="columns" :data="data" :loading="loading" />
    <div class="mt-4 flex justify-end">
      <NPagination
        v-model:page="page"
        v-model:page-size="pageSize"
        :item-count="total"
        show-size-picker
        :page-sizes="[10, 20, 50, 100]"
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </div>

    <NModal v-model:show="showModal" :title="modalTitle" preset="dialog" :loading="formLoading" :mask-closable="false" :style="{ width: '900px' }">
      <NDataTable :columns="detailColumns" :data="detailData" :bordered="false" />
      <template #action>
        <NButton @click="() => (showModal = false)">关闭</NButton>
      </template>
    </NModal>
  </Page>
</template>

<style scoped></style>
